<template>
  <div class="login">
    <div class="login-bg">
      <img src="../assets/logo/logo2.png" alt="">
      {{ title }}
    </div>
    <div class="login-content">
      <div class="login-form">
      <el-tabs v-model="activetabs">
        <!-- <el-tab-pane label="扫码登录" name="1">
          <div class="tips">请使用手机APP扫码登录</div>
          <img id="login_container" class="wxcode" :src="wxCode" alt="">
          <div style="float: right;margin-bottom: 32px;" v-if="register">
            <router-link class="link-type" :to="'/register'" style="color: rgba(0,0,0,0.25);font-size: 14px;">没有账号？</router-link>
          </div>
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width:100%;background: #29C1BA;"
            @click.native.prevent="getWechatQrcode"
          >
            <span >刷新</span>
          </el-button>
        </el-tab-pane> -->
        <el-tab-pane label="帐号登录" name="2">
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                type="text"
                auto-complete="off"
                placeholder="账号"
              >
                <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                auto-complete="off"
                placeholder="密码"
                @keyup.enter.native="handleLogin"
              >
                <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
            <el-form-item prop="code" v-if="captchaEnabled">
              <el-input
                v-model="loginForm.code"
                auto-complete="off"
                placeholder="验证码"
                style="width: 63%"
                @keyup.enter.native="handleLogin"
              >
                <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
              </el-input>
              <div class="login-code">
                <img :src="codeUrl" @click="getCode" class="login-code-img"/>
              </div>
            </el-form-item>
            <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
            <div style="float: right;margin-bottom: 32px;" v-if="register">
              <router-link class="link-type" :to="'/register'" style="color: rgba(0,0,0,0.25);font-size: 14px;">没有账号？</router-link>
            </div>
            <el-form-item style="width:100%;">
              <div style="display: flex;width: 100%;">
                <el-button
                  :loading="loading"
                  size="medium"
                  type="primary"
                  style="width:100%;background: #29C1BA;"
                  @click.native.prevent="handleLogin"
                >
                  <span v-if="!loading">登 录</span>
                  <span v-else>登 录 中...</span>
                </el-button>
                <el-button
                  size="medium"
                  type="primary"
                  style="width:100%;background: #29C1BA;"
                  @click.native.prevent="getWechatQrcode"
                >
                  <span>微信登录</span>
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      </div>
      <!--  底部  -->
      <div class="el-login-footer">
        <span>Copyright © 2025 深圳刑知文化传播有限公司</span>
      </div>
    </div>
  </div>
</template>

<script>
import qrcode from 'qrcode'
import { getCodeImg, wechatQrcode, requstUrlGet, wechatBind } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { setToken } from '@/utils/auth'

export default {
  name: "Login",
  data() {
    return {
      title: process.env.VUE_APP_TITLE,
      activetabs: '2',
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: true,
      redirect: undefined,
      wxCode: '',
      wxCodeId: '',
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  mounted() {
    if(this.$route.query.redirect && this.$route.query.redirect.indexOf('/wechatLogin') >= 0) {
      this.$modal.loading('登录中...')
      requstUrlGet(this.$route.query.redirect).then(async res => {
        this.$modal.closeLoading();
        if(res.code == 252) {
          this.$prompt('此微信未绑定账号,请输入绑定账号的手机号', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^(1[3-9])\d{9}$/,
            inputErrorMessage: '手机号格式不正确'
          }).then(({ value }) => {
            this.$modal.loading('微信绑定中...')
            wechatBind({state: res.msg, phone: value}).then(async bindRes => {
              this.$modal.closeLoading();
              if(bindRes.token) {
                setToken(bindRes.token)
                await this.$store.commit('SET_TOKEN', bindRes.token)
                this.$router.push({ path: "/index" }).catch(()=>{});
              }
            })
          }).catch(() => {
            this.$router.push({ query: {} })
          });
        } else if(res.code == 251 || res.code == 250 || res.code == 253 || res.code == 254) {
          this.$router.push({ query: {} })
        } else {
          setToken(res.token)
          await this.$store.commit('SET_TOKEN', res.token)
          this.$router.push({ path: "/index" }).catch(()=>{});
        }
      })
    }
  },
  methods: {
    getWechatQrcode() {
      const that = this
      wechatQrcode({}).then(res => {
        if(res.code == 200) {
          window.location = res.msg
        } else {
          that.$modal.msgError('获取微信登录链接失败')
        }
      })
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.el-tabs__item {
  color: rgba(0,0,0,0.25);
}
.el-tabs__item.is-active {
  color: #29C1BA;
}
.el-tabs__active-bar {
  background-color: #29C1BA;
}
.el-tabs__item:hover {
  color: #29C1BA;
}

.el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #29C1BA;
  border-color: #29C1BA;
}
.el-checkbox__input.is-focus .el-checkbox__inner {
  border-color: #29C1BA;
}
.el-checkbox__input.is-checked + .el-checkbox__label {
  color: #29C1BA;
}
.el-checkbox__inner:hover {
  border-color: #29C1BA;
}

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.login-bg {
  width: 50%;
  height: 100%;
  background-image: url("../assets/images/login.png");
  background-size: 100% 100%;
  display: flex;
  gap: 2px;
  padding: 45px;
  font-size: 16px;
  color: rgba(0,0,0,0.85);
  img {
    display: block;
    width: 83px;
    height: 18px;
  }
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-content {
  position: relative;
  width: 50%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-radius: 6px;
  background: #ffffff;
}
.login-form {
  position: relative;
  width: 326px;
  border-radius: 6px;
  background: #ffffff;
  .tips {
    font-size: 14px;
    color: rgba(0,0,0,0.85);
    text-align: center;
    margin-bottom: 12px;
  }
  .wxcode {
    display: block;
    width: 154px;
    height: 154px;
    margin: 0 auto;
    margin-bottom: 34px;
    border-radius: 4px;
    border: 1px solid rgba(0,0,0,0.1);
  }
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: absolute;
  bottom: 0;
  width: 100%;
  text-align: center;
  font-family: Arial;
  font-size: 12px;
  color: rgba(0,0,0,0.5);
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
</style>
